package com.example.xgakj.newterminal.models;

import android.app.Activity;

import com.example.xgakj.mylibrary.mvp.utils.ToastUtil;
import com.example.xgakj.newterminal.base.BaseApplication;
import com.example.xgakj.newterminal.base.Parameters;
import com.example.xgakj.newterminal.beans.CustomerTable;
import com.example.xgakj.newterminal.beans.ResultBean;
import com.example.xgakj.newterminal.utils.NetUtil;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.socks.library.KLog;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.List;

import static com.example.xgakj.newterminal.base.BaseApplication.usrID;


/**
 * @author Administrator
 * @date 2017-10-16
 */

public class QueryModel {
    private static volatile QueryModel mQueryModel;

    private QueryModel() {

    }

    public static QueryModel getInstance() {
        if (mQueryModel == null) {
            synchronized (QueryModel.class) {
                if (mQueryModel == null) {
                    mQueryModel = new QueryModel();
                }
            }
        }
        return mQueryModel;
    }

    /**
     * 查询客户的设备表
     *
     * @param ssn
     * @param usrID
     */
    public void queryDevices(String ssn, String usrID) {
        String queryUsr = "cust_id='00" + usrID + "'";
        String[] keys = {"table", "field", "param"};
        String[] values = {Parameters.VIDEODEVICE, "*", queryUsr};
        String json = NetUtil.toJSON(keys, values);
        OkGo.<String>post(BaseApplication.baseUrl)
                .isSpliceUrl(true)
                .params("cmd", "select")
                .params("ssn", BaseApplication.ssn)
                .params("usr", usrID)
                .upString(json)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        KLog.d(response.body().toString());
                    }
                });

    }

    /**
     * 通用网络访问方法
     *
     * @param cmd          命令，比如"select","login"
     * @param table        查询的表
     * @param field        查询的字段
     * @param param        指定的参数
     * @param jsonCallBack 回调
     * @param <T>          回调的javabean
     */
    public <T> void queryCommon(String cmd, String table, String field, String param, BaseJsonCallBack<T> jsonCallBack) {
        String[] keys = {"table", "field", "param"};
        String[] values = {table, field, param};
        String json = NetUtil.toJSON(keys, values);
        OkGo.<T>post(BaseApplication.baseUrl)
                .isSpliceUrl(true)
                .params("cmd", cmd)
                .params("ssn", BaseApplication.ssn)
                .params("usr", usrID)
                .upString(json)
                .execute(jsonCallBack);
    }

    /**
     * 通用网络访问方法
     *
     * @param cmd          命令，比如"select","login"
     * @param jsonCallBack 回调
     * @param <T>          回调的javabean
     */
    public <T> void sendCommand(String cmd, String[] keys, String[] values, BaseJsonCallBack<T> jsonCallBack) {

        String json = NetUtil.toJSON(keys, values);
        OkGo.<T>post(BaseApplication.baseUrl)
                .isSpliceUrl(true)
                .params("cmd", cmd)
                .params("ssn", BaseApplication.ssn)
                .params("usr", usrID)
                .upString(json)
                .execute(jsonCallBack);
    }


    /**
     * 查询客户资料
     *
     * @param ssn
     * @param userId
     */
    public void queryUserTable(String ssn, String userId) {
        String[] keys = {"table", "field", "param"};
        String[] values = {Parameters.CUSTOMER, "cuid,name,partid,status,recvtime,baoan,xunluo,police,address,note,dateend,CUPassWords", "cuid=" + userId};
        String json = NetUtil.toJSON(keys, values);
        OkGo.<String>post(BaseApplication.baseUrl)
                .isSpliceUrl(true)
                .params("cmd", "select")
                .params("ssn", BaseApplication.ssn)
                .params("usr", usrID)
                .upString(json)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        String responseJson = response.body().toString();
                        try {
                            JSONObject jsonObject = new JSONObject(responseJson);
                            String ret = jsonObject.getString("ret");
                            if (ret.equals("OK")) {
                                String objStr = jsonObject.getString("obj");
                                Gson gson = new Gson();
                                List<CustomerTable> list = gson.fromJson(objStr, new TypeToken<List<CustomerTable>>() {
                                }.getType());
                                CustomerTable customerTable = list.get(0);
                                EventBus.getDefault().post(customerTable);
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                });
    }

    /**
     * 更新表单
     *
     * @param table  表名称
     * @param kname  查询条件
     * @param kvalue 值
     * @param fname  字段
     * @param fvalue 字段值
     */
    public void updateInfo(String table, String kname, String kvalue, String fname, String fvalue, final NetCallBack callBack) {
        String[] keys = {"table", "kname", "kvalue", "fname", "fvalue"};
        String[] values = {table, kname, kvalue, fname, fvalue};
        String json = NetUtil.toJSON(keys, values);
        OkGo.<String>post(BaseApplication.baseUrl)
                .isSpliceUrl(true)
                .params("cmd", "select")
                .params("ssn", BaseApplication.ssn)
                .params("usr", usrID)
                .upString(json)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        KLog.d(response.body().toString());
                        if (response.body().toString().contains("OK")) {

                            ToastUtil.showShort(BaseApplication.context, "修改成功");
                            if (callBack != null) {
                                callBack.onSuccess();
                            }
                        } else {
                            ToastUtil.showShort(BaseApplication.context, "修改失败");
                            if (callBack != null) {
                                callBack.onFailure();
                            }
                        }
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        ToastUtil.showShort(BaseApplication.context, "修改失败,检查网络连接");
                        if (callBack != null) {
                            callBack.onFailure();
                        }
                    }
                });
    }

    public interface NetCallBack {
        void onSuccess();

        void onFailure();

    }

    /**
     * 一键远程报警
     */
    public void remoteAlarm(final Activity activity) {
        String[] keys = {"start_zone"};
        String[] values = {"91"};
        String json = NetUtil.toJSON(keys, values);
        OkGo.<ResultBean>post(BaseApplication.baseUrl)
                .isSpliceUrl(true)
                .params("cmd", "alm_st")
                .params("ssn", BaseApplication.ssn)
                .params("usr", usrID)
                .upString(json)
                .execute(new BaseJsonCallBack<ResultBean>(activity) {
                    @Override
                    public void onSuccess(Response<ResultBean> response) {

                        if (response.body().getRet().equals("OK")) {
                            ToastUtil.showShort(activity, "报警成功");
                        }
                    }
                });
    }

    public <T> void queryAlarmInfo(String field, String param, BaseJsonCallBack<T> jsonCallBack) {
        String[] keys = {"table", "field", "param"};
        String[] values = {Parameters.VIEW_YUYINALARMLOGS, field, param};
        String json = NetUtil.toJSON(keys, values);
        OkGo.<T>post(BaseApplication.baseUrl)
                .isSpliceUrl(true)
                .params("cmd", "select")
                .params("ssn", BaseApplication.ssn)
                .params("usr", BaseApplication.usrID)
                .upString(json)
                .execute(jsonCallBack);

    }

    /**
     * 更新
     */
    public void update(String table, String kname, String kvalue, String fname, String fvalue, StringCallback callback) {
        String[] keys = {"table", "kname", "kvalue", "fname", "fvalue"};
        String[] values = {table, kname, kvalue, fname, fvalue};
        String json = NetUtil.toJSON(keys, values);
        OkGo.<String>post(BaseApplication.baseUrl)
                .isSpliceUrl(true)
                .params("cmd", Parameters.UPDATE)
                .params("ssn", BaseApplication.ssn)
                .params("usr", usrID)
                .upString(json)
                .execute(callback);
    }

    /**
     * 分页查询表单
     * @param table 表名
     * @param field2 字段
     * @param param 条件
     * @param pquan 每页条数
     * @param pcurr 当年页面
     * @param kname 排序参数
     * @param ksoft 排序方式
     * @param jsonCallBack 回调
     * @param <T> 结果泛型
     */
    public<T> void getListByPage(String table, String field2, String param, String pquan, String pcurr, String kname, String ksoft, BaseJsonCallBack<T> jsonCallBack) {
        String[] keys = {"table", "field", "param", "pquan", "pcurr", "kname", "ksort"};
        String[] values = {table, field2, param, pquan, pcurr, kname, ksoft};
        String tojson = NetUtil.toJSON(keys, values);
        OkGo.<T>post(BaseApplication.baseUrl)
                .isSpliceUrl(true)
                .params("cmd", "select")
                .params("ssn", BaseApplication.ssn)
                .params("usr", BaseApplication.usrID)
                .upString(tojson)
                .execute(jsonCallBack);
    }


}
